//实现的核心思路 重写resolve函数
class CancelablePromise {
    /**
     * 构造器
     * @param executor Promise中的 executor 就是传入的函数 (resolve,reject)=>{}
     * @param abortSignal AbortController中的signal对象
     * @returns 
     */
    constructor(executor, abortSignal) {
        // 记录reject和resolve方法
        let _reject = null;
        let _resolve = null;
        //promise是否已经兑现,已经回调了resolve
        let _isExecResolve = false;
        // 创建和执行Promise
        const cancelablePromise = new Promise((resolve, reject) => {
            _reject = reject;
            _resolve = (value) => {
                //如果这个resolve被回调了,那么将状态扭转为true
                _isExecResolve = true;
                resolve(value);
            };
            executor(_resolve, reject);
        });
        // 监听Signal的abourt事件
        if (abortSignal) {
            abortSignal.addEventListener('abort', () => {
                if (_isExecResolve) {
                    return;
                }
                // 抛出错误
                const error = new DOMException('用户取消了propse', CancelablePromise.CancelExceptionName);
                _reject(error);
            });
        }
        return cancelablePromise;
    }
    // 取消后抛出的异常名称
    static CancelExceptionName = 'CancelablePromise AbortError';
}


export default CancelablePromise;
